package com.spzx.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.user.service.ISmsService;
import com.spzx.user.utils.HttpUtils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ClassName: SmsServiceImpl
 * Package: com.spzx.user.service.impl
 * Description:
 *
 * @Author 咚咚小圆帽
 * @Create 2025/3/25 13:44
 * @Version 1.0
 */
@Service
@Slf4j
public class SmsServiceImpl implements ISmsService {

    @Override
    public void sendCode(String phone, String templateId, Map<String, Object> param) throws Exception {
        String host = "https://dfsns.market.alicloudapi.com";
        String path = "/data/send_sms";
        String method = "POST";
        String appcode = "0bcbba97da52431fa8b5edfa7da545e0";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();

        String content = param.entrySet()
                .stream()
                //将每个键值对格式化为"key:value"，最后用逗号连接所有字符串
                .map(entry -> entry.getKey() + ":" + entry.getValue())
                .collect(Collectors.joining(","));

        bodys.put("content", content);
        bodys.put("template_id", templateId);  //注意，CST_ptdie100该模板ID仅为调试使用，调试结果为"status": "OK" ，即表示接口调用成功，然后联系客服报备自己的专属签名模板ID，以保证短信稳定下发
        bodys.put("phone_number", phone);


        /**
         * 重要提示如下:
         * HttpUtils请从
         * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
         * 下载
         *
         * 相应的依赖请参照
         * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
         */
        HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
        //HttpEntity entity = response.getEntity();
        //String result = EntityUtils.toString(entity, "UTF-8");
        //System.out.println(result);
        //获取response的body

        //不能获取两次，否则会出现io异常
//            System.out.println(EntityUtils.toString(response.getEntity()));

        String data = EntityUtils.toString(response.getEntity());
        HashMap<String, String> map = JSONObject.parseObject(data, HashMap.class);
        String status = map.get("status");
        if (!"OK".equals(status)) {
            log.error("短信发送失败：" + map.get("reason"));
            throw new ServiceException(map.get("reason"));
        }


    }
}
